/*
* @Author: z.p
* @Project: Zdotp
* @Date: 2025年01月01日
* @Description: 执行定时器逻辑的actor
*/

using Zdotp.Actor;
using Zdotp.Actor.Controller;
using Zdotp.Actor.Packet;
using Zdotp.Timer;

namespace TimerServer.Actors;

public class TimerTestActor : ActorBase
{
    protected override void OnAwake()
    {
        
    }

    protected override void OnStart()
    {
        
    }

    protected override void OnUpdate(float deltaTime)
    {
        
    }

    protected override void OnDestroy()
    {
        
    }
}

public class TestMessage : MailObject
{
    public string Data;
}
public class TimerTestHandler : ActorController<TimerTestActor, TestMessage>
{
    private ZTimer? _timer1;
    private ZTimer? _timer2;
    protected override void Run(TimerTestActor actor, ActorSystem system, MessageInfo info, TestMessage data)
    {
        try
        {
            switch (data.Data)
            {
                case "add1":
                    if (_timer1 != null)
                    {
                        actor.Logger.Error($"Timer1 is already exist");
                        break;
                    }

                    _timer1 = actor.MyActorSystem.CreateTimer(timer =>
                    {
                        // 默认不循环
                        // timer.IsLoop = false;
                        timer.AddKeyFrame(1, () => { actor.Logger.Info($"Timer1 is trigger [1s]"); });
                        timer.AddKeyFrame(2, () => { actor.Logger.Info($"Timer1 is trigger [2s]"); });
                    }, _ =>
                    {
                        _timer1 = null;
                    });
                    _timer1.Start(actor);
                    break;
                case "stop1":
                    _timer1?.StopTimer();
                    break;

                case "add2":
                    if (_timer2 != null)
                    {
                        actor.Logger.Error($"Timer2 is already exist");
                        break;
                    }

                    _timer2 = actor.MyActorSystem.CreateTimer(timer =>
                    {
                        timer.IsLoop = true;
                        timer.AddKeyFrame(0.5f, () => { actor.Logger.Info($"Timer2 (loop) is trigger [0.5s]"); });
                    },  _ =>
                    {
                        _timer2 = null;
                    });
                    _timer2.Start(actor);
                    break;
                case "stop2":
                    _timer2?.StopTimer();
                    break;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}